<template>
  <div class="pane-account">
    <el-form
      :model="account"
      label-width="60px"
      size="large"
      :rules="accountRules"
      status-icon
      ref="formRef"
    >
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" style="width: 220px"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="account.password"
          type="password"
          show-password
          style="width: 220px"
        ></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { ElForm, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import useLoginStore from '@/store/login/login'
import type { IAccount } from '@/types/login'
import { localCache } from '@/utils/cache'

const NAME = 'name'
const PASSWORD = 'password'

// 定义account数据
const account = reactive<IAccount>({
  name: localCache.getCache(NAME) ?? '',
  password: localCache.getCache(PASSWORD) ?? ''
})

// 定义校验规则
const accountRules: InstanceType<typeof FormRules> = {
  name: [
    {
      required: true,
      message: '必须输入账号信息~',
      trigger: 'blur'
    },
    {
      pattern: /^[a-z0-9]{6,20}$/,
      message: '必须是6-20位数字或字母组成~',
      trigger: 'change'
    },
    {
      pattern: /^[a-z0-9]{6,20}$/,
      message: '必须是6-20位数字或字母组成~',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '必须输入密码信息~', trigger: 'blur' },
    { pattern: /^[a-z0-9]{3,}$/, message: '必须是3位以上数字或字母', trigger: 'change' },
    { pattern: /^[a-z0-9]{3,}$/, message: '必须是3位以上数字或字母', trigger: 'blur' }
  ]
}

// 执行账号登录的逻辑
const formRef = ref<InstanceType<typeof ElForm>>()

const loginStore = useLoginStore()

function loginAction(isRemPwd: boolean) {
  formRef.value?.validate((valid) => {
    if (valid) {
      // console.log('验证成功', '登录的操作')
      const name = account.name
      const password = account.password
      loginStore.loginAccountAction({ name, password })
      if (isRemPwd) {
        localCache.setCache(NAME, name)
        localCache.setCache(PASSWORD, password)
      } else {
        localCache.removeCache(NAME)
        localCache.removeCache(PASSWORD)
      }
    } else {
      ElMessage.error('请您输入正确的格式后再操作~~')
    }
  })
}

defineExpose({ loginAction })
</script>

<style lang="less" scoped></style>
